<!--
 * @Descripttion: 说明
 * @version: V1.0
 * @Author: fgz
 * @Date: 2021-10-25 11:35:47
 * @LastEditors: fgz
 * @LastEditTime: 2021-10-25 17:55:22
-->
<template>
  <div id="app">
    <Header></Header>
    <Goods
      v-for="item in list"
      :key="item.id"
      :id="item.id"
      :title="item.goods_name"
      :pic="item.goods_img"
      :price="item.goods_price"
      :state="item.goods_state"
      :count="item.goods_count"
      @state-change="changeState"
    ></Goods>
    <!-- Footer区域 -->
    <Footer :isfull="fullSate" :amount="amt" :all="total" @full-change="getFullState"></Footer>
  </div>
</template>

<script>
import axios from "axios";
import Header from "./components/Header/Header.vue";
import Goods from "./components/Goods/Goods.vue";
import Footer from "./components/Footer/Footer.vue";
import bus from "@/components/eventBus.js"

export default {
  name: "App",
  components: {
    Header,
    Goods,
    Footer
  },
  data() {
    return {
      list: [], // 用来存储购物车的列表数据，默认为空数组
    };
  },
  // 计算属性
  computed: {
    // 动态计算出全选的状态 true 还是 false
    fullSate() {
      return this.list.every(item => item.goods_state )
    },
    // 已勾选商品的总价
    amt(){
      // 先filter过滤
      return this.list.filter(item=> item.goods_state).reduce((total, item)=>(
        total += item.goods_price * item.goods_count
      ), 0)
    },
    // 已勾选商品的总数量
    total() {
      return this.list.filter(item=> item.goods_state).reduce((t,item) => ( t += item.goods_count
      ),0)
    }
  },
  created() {
    this.initCartList();
    // 接收数据
    bus.$on('share',val=>{
      this.list.some(item => {
        if(item.id === val.id){
          item.goods_count = val.value
          return true
        }
      })
    })
  },
  methods: {
    // 封装请求列表数据的方法
    async initCartList() {
      // 调用 axios的get 方法，请求列表数据
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      if (res.status === 200) {
        this.list = res.list;
      }
      console.log(res);
    },
    // 接收子组件传递过来的数据
    // e的格式{id, value}
    changeState(e){
      this.list.some(item=>{
        if(item.id === e.id) {
          item.goods_state = e.value
          // 终止后续的循环
          return true;
        }
      })
    },
    getFullState(val){
      this.list.forEach(item=>(item.goods_state = val))
    }
  },
};
</script>

<style lang="less">
#app {
  // padding-top: 45px;
  padding-bottom: 50px;
}
</style>
